<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      v-show="showSearch"
    >
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="文件标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label='' prop="createTime">
        <el-date-picker
          clearable
          style="width: 100%"
          v-model="createTime"
          type="daterange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00','23:59:59']"
          range-separator="-"
          start-placeholder="创建开始日期"
          end-placeholder="创建结束日期"
        ></el-date-picker>
      </el-form-item>
      </el-col>
    </el-row>
      
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <right-toolbar @dataChange="dataChange" :storageKey="$options.name" @changeColumns="changeColumns" ref="table" :showSearch.sync="showSearch" @queryTable="getList"
      :columns="columns"></right-toolbar>-->
      <right-toolbar ref="table" :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- <el-table row-key="key" :key="isShow" v-loading="loading" :data="downloadList" ref="downloadTable"  @selection-change="handleSelectionChange">
      <template v-for="item in columns">
        <el-table-column v-if="item.visible && item.type" type="selection" :key="Math.random()" width="55"
                         align="center"
        ></el-table-column>
        <el-table-column :key="Math.random()" v-if="item.visible && !item.type" :class-name="item.className"
                         :prop="item.prop"
                         :label="item.label" :align="item.align" :type="item.type" :width="item.width"
        >
          <template slot-scope="scope">
            <template v-if="item.htmlType == 'imageUpload' && item.visible">
              <image-preview :src="scope.row[item.prop]" :width="50" :height="50"/>
            </template>

          <template v-else-if="item.htmlType == 'datetime' && item.visible">
            <span>{{ parseTime(scope.row[item.prop], '{y}-{m}-{d}') }}</span>
          </template>

          <template v-else-if="item.htmlType == 'checkbox' && item.visible" >
                <dict-tag v-if="item.htmlType == 'checkbox'" :options="dict.type[item.dictType]"
                          :value="scope.row[item.prop] ? scope.row[item.prop].split(',') : []"/>
                <dict-tag v-else :options="dict.type[item.dictType]" :value="scope.row[item.prop]"/>
          </template>
          <template v-else-if="item.htmlType =='operation'">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:download:edit']"
          >修改</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:download:remove']"
          >删除</el-button>
        </template>
          <template v-else>
            <span>{{ scope.row[scope.column.property] }}</span>
          </template>
          </template>
        </el-table-column>
      </template>

    </el-table>-->
    <el-table
      v-loading="loading"
      :data="downloadList"
      ref="downloadTable"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="文件标题" align="left" prop="title" />
      <el-table-column label="操作人" align="center" prop="createBy" />
      <el-table-column label="下载次数统计" align="center" prop="downloadCount" />
      <el-table-column label="创建日期" sortable align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增或修改下载对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容介绍" prop="content">
          <!-- <editor v-model="form.content" :min-height="192" /> -->
          <JEditor :key="showdis" v-model="form.content" :height="350"/>
        </el-form-item>
        <el-form-item label="附件" prop="downUrl">
                <RoadUpload
                  v-model="form.downUrl"
                  :fileType="fileType"
                  :fileSize="fileSize"
                  :limit="limit"
                  :flag="isFlag"
                ></RoadUpload>
              </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">返 回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDownload,
  getDownload,
  delDownload,
  addDownload,
  updateDownload
} from "@/api/information/download/download.js";
import RoadUpload from "../../../components/RoadUpload/index.vue";
// import { setStorageItem, getStorageItem } from "@/utils/storage.js";
// import Sortable from "sortablejs";
export default {
  name: "Download",
  components: {
    RoadUpload,
  },
  data() {
    return {
      limit:1,
      // 是否显示格式
      isFlag:false,
      isShow: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      titles: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 下载表格数据
      downloadList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      showdis:123,
      // 时间范围
      createTime:'',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
      },
      // 列信息
      // columns: [
      //       {key: -1, label:  'ID', visible: true, prop: 'id', htmlType:'input',dictType:'',align:'center'},
      //       {key: 0, label:  '标题', visible: true, prop: 'title', htmlType:'input',dictType:'',align:'center'},
      //       {key: 1, label:  '作者', visible: true, prop: 'author', htmlType:'input',dictType:'',align:'center'},
      //       {key: 2, label:  '文件网址', visible: true, prop: 'downUrl', htmlType:'input',dictType:'',align:'center'},
      //       {key: 3, label:  '内容介绍', visible: true, prop: 'content', htmlType:'editor',dictType:'',align:'center'},
      //       {key: 4, label:  '状态：0-未发布 1-已发布', visible: true, prop: 'status', htmlType:'radio',dictType:'',align:'center'},
      //       {key: 5, label:  '顺序', visible: true, prop: 'sequence', htmlType:'input',dictType:'',align:'center'},
      //       {key: 6, label:  '来源', visible: true, prop: 'source', htmlType:'input',dictType:'',align:'center'},
      //       {key: 7, label:  '创建者', visible: true, prop: 'createBy', htmlType:'input',dictType:'',align:'center'},
      //       {key: 8, label:  '创建时间', visible: true, prop: 'createTime', htmlType:'datetime',dictType:'',align:'center'},
      //       {key: 9, label:  '更新者', visible: true, prop: 'updateBy', htmlType:'input',dictType:'',align:'center'},
      //       {key: 10, label:  '更新时间', visible: true, prop: 'updateTime', htmlType:'datetime',dictType:'',align:'center'},
      //       {key: 11, label:  '备注', visible: true, prop: 'remark', htmlType:'textarea',dictType:'',align:'center'},
      //       {key: 12, label:  '租户ID', visible: true, prop: 'tenantId', htmlType:'input',dictType:'',align:'center'},
      //   {key: 0, label: `操作`, visible: true, prop: 'operation', htmlType: 'operation', align: 'center', width: '200', className: 'fixed-width'}
      // ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [{ required: true, message: "文件标题不能为空", trigger: "blur" }],
        content: [{ required: true, message: "内容介绍不能为空", trigger: "blur" }],
        downUrl: [
          { required: true, message: "附件不能为空", trigger: "blur" }
        ]
      },
      fileType: [],
      fileSize:50,
    };
  },
  created() {
    // let data = getStorageItem(this.$options.name)
    // if(data) {
    //   this.columns=data
    // }
    this.getList();
  },
  //  mounted() {
    
  // },
  methods: {
    //列拖拽
    // columnDrop() {
    //   const wrapperTr = this.$refs.downloadTable.$el.querySelector('.el-table__header-wrapper tr');
    //   this.sortable = Sortable.create(wrapperTr, {
    //     animation: 180,
    //     delay: 30,
    //     // draggable: ".drag",
    //     onEnd: evt => {
    //       if (evt.oldIndex === evt.newIndex) return;
    //       const oldItem = this.columns[evt.oldIndex];
    //       const newItem = this.columns[evt.newIndex];
    //       this.$set(this.columns, evt.newIndex, oldItem);
    //       this.$set(this.columns, evt.oldIndex, newItem);
    //       setStorageItem(this.$options.name, this.columns)
    //     },
    //   });
    // },
    // dataChange(data){
    //   for (let item in this.columns) {

    //     const key = this.columns[item].key;
    //     this.columns[item].visible = !data.includes(key);
    //   }

    //   setStorageItem(this.$options.name, this.columns)
    // },
    // changeColumns(data) {
    //   this.columns=data
    //   setStorageItem(this.$options.name,data)
    //   this.isShow  = !this.isShow
    // },
    /** 查询下载列表 */
    getList() {
      this.loading = true;
      listDownload(this.addDateRange(this.queryParams,this.createTime)).then(response => {
        this.downloadList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        author: null,
        downUrl: null,
        content: null,
        status: 0,
        sequence: null,
        source: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        tenantId: null
      };
      this.fileType = [],
      this.fileSize = 50
      this.resetFormData("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.createTime=[]
      this.resetFormData("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.titles = selection.map(item => item.title);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 调用字典接口
    async gitDictType() {
      const res = await this.getDicts('attr_type')
      const Arr = res.data
      Arr.map(item => {
        return this.fileType.push(item.dictLabel)
      })
      const resSize = await this.getDicts('attr_size')
      this.fileSize = Number(resSize.data[0].dictValue)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.gitDictType()
      this.open = true;
      this.showdis = Math.random();
      this.title = "新增下载";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.gitDictType()
      const id = row.id || this.ids;
      getDownload(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.showdis = Math.random();
        this.title = "修改下载";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDownload(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDownload(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const titles = row.title || this.titles;
      this.$modal
        .confirm('是否确认删除文件标题为"' + titles + '"的数据项？')
        .then(function() {
          return delDownload(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/download/export",
        {
          ...this.queryParams
        },
        `download_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
